import dayjs from 'dayjs';

const zeroTime = new Date('0001-01-01T00:00:00Z');
export const diffDate = (time) => {
  const timestamp = new Date(time).getTime();
  if (timestamp === zeroTime.getTime()) {
    return '';
  }
  const refTimestamp = Date.now();
  let diffTimestamp = refTimestamp - timestamp;
  if (diffTimestamp <= 0) {
    // 兼容小米手机出现1s以内的负值情况
    diffTimestamp = 0;
  }
  const diffSeconds = Math.floor(diffTimestamp / 1000);
  const diffMinutes = Math.floor(diffSeconds / 60);
  const diffHours = Math.floor(diffSeconds / 3600);
  const diffDays = Math.floor(diffSeconds / 86400);
  if (diffDays === 0 && diffHours === 0 && diffMinutes === 0) {
    return '刚刚';
  }
  if (diffDays === 0 && diffHours === 0) {
    return `${diffMinutes}分钟前`;
  }
  if (diffDays === 0) {
    return `${diffHours}小时前`;
  }
  if (diffDays === 1) {
    return '昨天';
  }
  if (diffDays === 2) {
    return '前天';
  }
  return dayjs(time).format('YYYY-MM-DD');
};

export function isLive(time) {
  const now = new Date().getTime();
  const times = new Date(time).getTime();
  console.log(now - times);
  return now - times < 60 * 60 * 24 * 1000;
}

export function subDate(start, end) {
  const startTimestamp = new Date(start).getTime();
  const endTimestamp = new Date(end).getTime();
  if (endTimestamp === zeroTime.getTime()) {
    return '';
  }
  let diffTimestamp = endTimestamp - startTimestamp;
  if (diffTimestamp <= 0) {
    // 兼容小米手机出现1s以内的负值情况
    diffTimestamp = 0;
  }
  const diffSeconds = Math.floor(diffTimestamp / 1000);
  const diffMinutes = Math.floor(diffSeconds / 60);
  const diffHours = Math.floor(diffSeconds / 3600);
  const diffDays = Math.floor(diffSeconds / 86400);

  if (diffDays === 0 && diffHours === 0 && diffMinutes === 0) {
    return `${diffSeconds || 1}秒`;
  }
  if (diffDays === 0 && diffHours === 0) {
    return `${diffMinutes}分钟`;
  }
  if (diffDays === 0) {
    return `${diffHours}小时`;
  }
  return `${diffDays}天`;
}

export const nowTimeScope = () => {
  const hours = new Date().getHours();
  if (hours >= 0 && hours < 6) {
    return '凌晨';
  }
  if (hours >= 6 && hours < 8) {
    return '早上';
  }
  if (hours >= 8 && hours < 11) {
    return '上午';
  }
  if (hours >= 11 && hours < 13) {
    return '中午';
  }
  if (hours >= 13 && hours < 16) {
    return '下午';
  }
  if (hours >= 16 && hours < 19) {
    return '傍晚';
  }
  if (hours >= 19 && hours < 22) {
    return '晚上';
  }
  if (hours >= 22 && hours < 24) {
    return '深夜';
  }
  return '您';
};
